/**
 * 
 */
package pt.inescid.components.messages;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.NodeHandleSet;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import rice.p2p.commonapi.rawserialization.RawMessage;
import rice.pastry.NodeSet;

/**
 * @author Sergio Esteves (sesteves at gsd.inesc-id.pt)
 *
 */
public class AvailabilityMsg implements RawMessage {

	public static final short TYPE = 5;
	
	public final static String STATUS_STR[] = 
	{"IS_AVAILABLE", "AVAILABLE", "NOT_AVAILABLE"};
	
	public final static short IS_AVAILABLE = 0;	
	public final static short AVAILABLE = 1;
	public final static short NOT_AVAILABLE = 2;
	
	private NodeHandleSet source;
	
	private short status = 0; 	
	
	private double ratio;
	
	private static final long serialVersionUID = 7526472295622776147L;
	
	public AvailabilityMsg(NodeHandle source) {
		this.source = new NodeSet();
		this.source.putHandle(source);
	}

	public AvailabilityMsg(NodeHandle source, short status) {
		this(source);
		this.status = status;
	}
	
	public short getType() {		
		return TYPE;
	}

	public int getPriority() {
		return Message.LOW_PRIORITY;
	}
	
	public Id getSource() {
		return source.getHandle(0).getId();
	}
	
	public short getStatus() {
		return status;
	}
	public double getRatio() {
		return ratio;
	}
	
	public void setSource(NodeHandle source) {
		this.source = new NodeSet();
		this.source.putHandle(source);
	}
	public void setStatus(short status) {
		this.status = status;
	}
	public void setRatio(double ratio) {
		this.ratio = ratio;
	}
	
	public String toString() {	
		return "source: " + getSource() + ", status: " + STATUS_STR[status];
	}
	
	public AvailabilityMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		source = endpoint.readNodeHandleSet(buf, buf.readShort());
		status = buf.readShort();
		ratio = buf.readDouble();
	}

	public void serialize(OutputBuffer buf) throws IOException {
		buf.writeShort(source.getType());
		source.serialize(buf);
		buf.writeShort(status);
		buf.writeDouble(ratio);
	}
}
